﻿using Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;

public static class RequestExtensions
{
    /// <summary>
    /// 服务器的私钥，用来解密客户端的AES密钥
    /// </summary>
    const string RSA_PRIKEY = "gADGdK4rusQ3nT3vW6jdjv8c0afIYzqK4aL0fVQ09uAorXTswoK89HP4KlZOA/ZtfA+ZsyYaWgrOgLZlUWMHWQDSSk1JfZcF9djUqvwqVuO8jtiDwjPUm+5i5XdR3Ga1QWQ5AsnAnKndSYehjxAsBSdr1LgaLOiDZV8tS3M1QOBBtDmgIFaT+c6m3fICkGh9kTkXhZ+/0rGcI7aErHJRHdWyFc9bWvZ05cWdFAbIAgpu3kXhIFRn2f2QwOm8NJyW6JzczzNJASL0mLP9HNs1i8TD7ioEvbOsXXAbV1o7I9+q0eM+BwO3K5iYGFV5xNvbbrGECN8QQTv3H3TkGwLRLDU=";

    public static async Task<T> GetAsync<T>(this HttpRequestMessage request)
    {
        //从Header提取加密后的客户端AES密钥
        var aesKeyEnc = request.Headers.GetValues("key").First();

        //用RSA解密得到客户端的AES密钥
        var aesKey = RSAHelper.Decrypt(aesKeyEnc, RSA_PRIKEY);

        var bytes = await request.Content.ReadAsByteArrayAsync();
        var modelStrEnc = Encoding.UTF8.GetString(bytes);

        //用AES密钥解密传输内容
        var modelStr = AESHelper.Decrypt(modelStrEnc, aesKey);

        //反序列化成对象，拿到请求的参数
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(modelStr);
    }

    public static HttpResponseMessage Respond<T>(this HttpRequestMessage request, T model)
    {
        //从Header提取加密后的客户端AES密钥
        var aesKeyEnc = request.Headers.GetValues("key").First();

        //用RSA解密得到客户端的AES密钥
        var aesKey = RSAHelper.Decrypt(aesKeyEnc, RSA_PRIKEY);

        //序列化成对象，输出给客户端
        var modelModifiedStr = Newtonsoft.Json.JsonConvert.SerializeObject(model);

        var bytes = Encoding.UTF8.GetBytes(AESHelper.Encrypt(modelModifiedStr, aesKey));

        //序列化成对象，输出给客户端
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(bytes);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }
}